package com.team.auth.service;

import com.team.auth.domain.BizMerchantInfo;
import com.team.auth.domain.BizShopCertificates;
import com.team.auth.form.MerchantRegisterBody;
import com.team.auth.mapper.BizMerchantInfoMapper;
import com.team.auth.mapper.BizShopCertificatesMapper;
import com.team.common.core.constant.SecurityConstants;
import com.team.common.core.domain.R;
import com.team.system.api.RemoteUserService;
import com.team.system.api.domain.SysUser;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.security.SecureRandom;
import java.sql.Time;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

@Service
public class SysRegisterService {

    @Resource
    private RemoteUserService remoteUserService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private BizShopCertificatesMapper certificatesMapper;
    @Resource
    private BizMerchantInfoMapper merchantInfoMapper;

    @Transactional
    public void registerByMerchant(MerchantRegisterBody body) {

        // 3. 创建系统用户（操作员）
        SysUser user = createSysUser(body);
        R<Long> res = remoteUserService.registerMerchant(user, SecurityConstants.INNER);
        if (res.getCode() != 200) {
            throw new RuntimeException("注册操作员失败: " + res.getMsg());
        }
        user.setUserId(res.getData());


        // 4. 保存证件信息
        BizShopCertificates certificate = createCertificate(body);
        int insert = certificatesMapper.insert(certificate);
        if (insert <= 0) {
            throw new RuntimeException("保存商户证件信息失败");
        }

        // 5. 创建商户信息
        BizMerchantInfo merchant = createMerchantInfo(body, user.getUserId(), certificate.getId());
        merchantInfoMapper.insert(merchant);
        if (merchant.getId() == null) {
            throw new RuntimeException("保存商户信息失败");
        }

    }

    private SysUser createSysUser(MerchantRegisterBody body) {
        SysUser user = new SysUser();
        user.setUserName("merchant_"+ System.currentTimeMillis()); // 使用手机号作为登录账号
        user.setNickName(body.getOwnerName()); // 经营者姓名作为昵称
        user.setRealName(body.getOwnerName());
        user.setPhonenumber(body.getPhone());
        user.setPassword(passwordEncoder.encode(generateInitialPassword())); // 初始密码
        user.setAvatar("http://127.0.0.1:9300/statics/2025/07/10/1638860271747163886027116_20250710192153A001.jpg");
        user.setStatus("0"); // 正常状态
        user.setDelFlag("0"); // 未删除
        user.setCreateTime(new Date());
        return user;
    }

    private BizShopCertificates createCertificate(MerchantRegisterBody body) {
        BizShopCertificates certificate = new BizShopCertificates();
        certificate.setDirector(body.getOwnerName());
        certificate.setIdCard(body.getIdNumber());
        certificate.setMobile(body.getPhone());
        certificate.setBusinessLicenseId(body.getBusinessLicense());
        certificate.setBusinessLicenseImg(body.getBusinessLicensePhoto());
        certificate.setFront(body.getIdCardFront());
        certificate.setOpposite(body.getIdCardBack());
        return certificate;
    }

    private BizMerchantInfo createMerchantInfo(MerchantRegisterBody body, Long userId, Long certificateId) {
        BizMerchantInfo merchant = new BizMerchantInfo();
        merchant.setMerchantName(body.getShopName());
        merchant.setAddress(body.getAddress());
        merchant.setOperatingArea(body.getArea());
        merchant.setLongitude(BigDecimal.valueOf(body.getLongitude()));
        merchant.setLatitude(BigDecimal.valueOf(body.getLatitude()));
        merchant.setContactName(body.getOwnerName());
        merchant.setContactPhone(body.getPhone());
        merchant.setPhoto(body.getStoreFront());
        merchant.setRegTime(new Date());
        merchant.setStarAmount(BigDecimal.ZERO); // 初始星级0
        merchant.setSales(0); // 初始销量0
        merchant.setStartTime(Time.valueOf("08:00:00")); // 默认营业时间
        merchant.setEndTime(Time.valueOf("22:00:00"));
        merchant.setAuditStatusId(0); // 待审核状态
        merchant.setStatus("0"); // 正常状态
        merchant.setDelFlag("0"); // 未删除
        merchant.setUserId(userId);
        merchant.setCertificateId(certificateId.intValue());
        return merchant;
    }

    private String generateInitialPassword() {
        return "Merchant666666";
    }

}
